<?

class bf_validator {

	private $rules;

	public function __construct() {
		$this->rules = array();
	}

	public function rule_str($name, $required = false, $error_message = '', $min_length = 1) {
		$this->rule_regex($name, ($required ? '/^.{' . $min_length . ',}$/' : '/^(.{' . $min_length . ',})?$/'), $error_message);
	}

	public function rule_date($name, $required = false, $error_message = '') {
		$this->rule_regex($name, ($required ? '/^\d{4}\-\d{2}\-\d{2}$/' : '/^(\d{4}\-\d{2}\-\d{2})?$/'), $error_message);
	}

	public function rule_int($name, $required = false, $error_message = '') {
		$this->rule_regex($name, ($required ? '/^\-?[1-9]\d*$/' : '/^(\-?[1-9]\d*)?$/'), $error_message);
	}

	public function rule_pos_int($name, $required = false, $error_message = '') {
		$this->rule_regex($name, ($required ? '/^[1-9]\d*$/' : '/^([1-9]\d*)?$/'), $error_message);
	}

	public function rule_neg_int($name, $required = false, $error_message = '') {
		$this->rule_regex($name, ($required ? '/^\-[1-9]\d*$/' : '/^(\-[1-9]\d*)?$/'), $error_message);
	}

	public function rule_regex($name, $regex, $error_message = '') {
		$this->rules[$name] = (object) array(
			'regex' => $regex,
			'error_message' => $error_message,
		);
	}

	public function rule_float($name, $required = false, $error_message = '') {
		$this->rule_regex($name, ($required ? '/^\-?[1-9]\d*([\.\,]\d+)?$/' : '/^(\-?[1-9]\d*([\.\,]\d+)?)?$/'), $error_message);
	}

	public function rule_pos_float($name, $required = false, $error_message = '') {
		$this->rule_regex($name, ($required ? '/^[1-9]\d*([\.\,]\d+)?$/' : '/^([1-9]\d*([\.\,]\d+)?)?$/'), $error_message);
	}

	public function rule_neg_float($name, $required = false, $error_message = '') {
		$this->rule_regex($name, ($required ? '/^\-[1-9]\d*([\.\,]\d+)?$/' : '/^(\-[1-9]\d*([\.\,]\d+)?)?$/'), $error_message);
	}

	public function errors($fields) {
		$result = array();
		if (!is_array($fields)) {
			$fields = array($fields);
		}
		foreach ($fields as $name) {
			if (!@$this->rules[$name]) {
				continue;
			}
			$rule = $this->rules[$name];
			if (!preg_match($rule->regex, bf::$request->get($name))) {
				$result[$name] = $rule->error_message;
			}
		}
		return (count($result) ? $result : false);
	}
}

?>